package neichuan.center;

import io.netty.channel.Channel;
import neichuan.server.browser.BrowserServer;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class RegistCenter {

    //key存放server的port,ExchangeCenter对应mainChannel和临时使用的通道
    ConcurrentMap<Integer,ExchangeCenter> portExchangeCenterMap=new ConcurrentHashMap<>();
    BrowserServer browserServer=new BrowserServer();

    Object registPortLock=new Object();

    //synchronized
    /**
     * 注册主通道，成功返回true
     * @param port
     * @param mainChannel
     * @return
     */
    public boolean registPort(int port, Channel mainChannel) {
        if(portExchangeCenterMap.containsKey(port)){
            return false;
        }
        synchronized (registPortLock) {
            if(portExchangeCenterMap.containsKey(port)){
                return false;
            }
            portExchangeCenterMap.put(port, new ExchangeCenter(mainChannel));
        }

        //注册成功
        return true;
    }

    //synchronized
    /**
     * 注册主通道，并启动服务器，成功返回true
     * @param port
     * @param mainChannel
     * @return
     */
    public boolean registPortAndStart(int port, Channel mainChannel){
        boolean b = registPort(port, mainChannel);
        if(!b){
            return false;
        }
        b=addBrowserServer(port);
        if(b==false){
            //启动失败，从集合中删除
            remove(port,mainChannel);
        }
        return b;
    }

    //synchronized
    /**
     * 添加浏览器服务器
     * @param port
     * @return
     */
    public boolean addBrowserServer(int port) {
        try {
            Channel browserServerChannel = browserServer.addServer(port);
            portExchangeCenterMap.get(port).addBrowserServerChannel(browserServerChannel);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    //synchronized
    /**
     * 移除该port，并关闭对应的所有通道
     * @param port
     * @param mainChannel
     */
    public void remove(int port,Channel mainChannel) {
        ExchangeCenter remove = portExchangeCenterMap.get(port);
        boolean isRemove = false;
        if(remove!=null){
            Channel mc = remove.getMainChannel();
            isRemove=(mainChannel==mc);
        }

        if(isRemove){
            portExchangeCenterMap.remove(port);;
            //关闭该url对应的所有通道，释放资源
            remove.close();
        }
    }

    public void close(){
        browserServer.close();
    }


    public ExchangeCenter getExchangeCenter(int port){
        return portExchangeCenterMap.get(port);
    }
}
